public class BackgroundScroller{

  int previousUpdate, updateInterval, location1, location2, enteringBackground, leavingBackground;
  PImage backgrounds[];
  int currentImage, pixelsMovedPerInterval;  

  public BackgroundScroller(PImage images[], int updateInterval, int pixelsMovedPerInterval){
    if(images.length == 1){
      backgrounds = new PImage[2];
      backgrounds[0] = images[0];
      backgrounds[1] = images[0]; 
    } 
    else {
      backgrounds = images;
    }
    for(int i = 0; i < backgrounds.length; i++){
     image(backgrounds[i], -1922, 0); 
    }
    this.updateInterval = updateInterval;
    currentImage = 0;
    location1 = 0;
    location2 = width;
    leavingBackground = 0;
    enteringBackground = 1;
    this.pixelsMovedPerInterval = pixelsMovedPerInterval;
  }

  private void switchBackgroundsIfNecessary(){
    if(location1 <= (-width)){
      location1 = 0;
      location2 = width;
      leavingBackground = enteringBackground;
      if(enteringBackground == backgrounds.length-1){
        enteringBackground = 0; 
      } 
      else {
        enteringBackground++; 
      }
    }
  }

  public void updateBackground(int currentTime){
    switchBackgroundsIfNecessary();
    if(currentTime - previousUpdate > updateInterval){
      location1 = location1 - pixelsMovedPerInterval;
      location2 = location2 - pixelsMovedPerInterval;;
      previousUpdate = currentTime;
    }
    image(backgrounds[leavingBackground], location1, 0);
    image(backgrounds[enteringBackground], location2, 0);
  }

}

